package com.qf.agro.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qf.agro.common.ResultInfo;
import com.qf.agro.mapper.DeviceDataLogsMapper;
import com.qf.agro.pojo.SmartDeviceDataLogs;
import com.qf.agro.service.DeviceDataLogsService;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @author 10202
 * @version V1.0
 * @Project smart-agriculture-parent
 * @Package com.qf.agro.service.impl
 * @Date 2023/7/4 15:05
 */
@Service
public class DeviceDataLogsServiceImpl implements DeviceDataLogsService {
    @Autowired
    private DeviceDataLogsMapper deviceDataLogsMapper;
    @Override
    public ResultInfo getPage(Integer pageNum, Integer pageSize, Long facilitiesId, Long deviceId, Integer day, Integer resultCode) {

        Page<SmartDeviceDataLogs> pages=new Page<>(pageNum,pageSize);
        LambdaQueryWrapper<SmartDeviceDataLogs> lqw=new LambdaQueryWrapper<>();
        lqw.eq(facilitiesId!=null,SmartDeviceDataLogs::getFacilitiesId,facilitiesId);
        lqw.eq(deviceId!=null,SmartDeviceDataLogs::getDeviceId,deviceId);
        lqw.eq(SmartDeviceDataLogs::getResultCode,resultCode);
        if(day!=null){
            lqw.ge(SmartDeviceDataLogs::getCreateTime, DateUtils.addDays(new Date(),-day));
        }
       pages= deviceDataLogsMapper.selectPage(pages,lqw);

        return ResultInfo.success(pages);
    }

    @Override
    public List<SmartDeviceDataLogs> findList(Long facilitiesId, Long deviceId, Integer day, Integer resultCode) {
        LambdaQueryWrapper<SmartDeviceDataLogs> queryWrapper = new LambdaQueryWrapper<>();
        //2.设置条件
        queryWrapper.eq(facilitiesId != null,SmartDeviceDataLogs::getFacilitiesId,facilitiesId);
        queryWrapper.eq(deviceId!=null,SmartDeviceDataLogs::getDeviceId,deviceId);
        queryWrapper.eq(resultCode!= null,SmartDeviceDataLogs::getResultCode,resultCode);
        if(day!=null){
            //计算时间可以使用以下代码
            long currentMillis = System.currentTimeMillis();
            long millis = day*24*60*60*1000;
            long dateTimeMillis = currentMillis - millis;
            Date date = new Date(dateTimeMillis);
            queryWrapper.ge(SmartDeviceDataLogs::getCreateTime,date);
        }
        //3.发起查询
        List<SmartDeviceDataLogs> smartDeviceDataLogs = deviceDataLogsMapper.selectList(queryWrapper);
        //4.返回
        return smartDeviceDataLogs;
    }
}
